package com.web.my12306.controller;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util.HashMap;
import java.util.Map;

/**
 * @author 郭明亮抄的
 *
 */
public class InnerDispatcherController extends HttpServlet {

	private Map<String, Method> actions = new HashMap<>();

	@Override
	public void init() throws ServletException {
		super.init();

		Method[] methods = this.getClass().getMethods();
		Method method = null;
		for (int i = 0; i < methods.length; i++) {
			method = methods[i];

			if (method.getModifiers() == Modifier.PUBLIC) {
				actions.put(this.getServletContext().getContextPath() + "/" + this.getServletName() + "/"
						+ method.getName(), method);
			}
		}
	}

	@Override
	protected void service(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		String uri = request.getRequestURI();
		Method action = actions.get(uri);
		if (null != action) {
			try {
				action.invoke(this, request , response);
			} catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException e) {
				e.printStackTrace();
			}
		}
	}
}
